//
//  StateMachineModel.m
//  LearnObjectiveC
//
//  Created by client on 2017/9/18.
//  Copyright © 2017年 吴可高. All rights reserved.
//

#import "StateMachineModel.h"

NSString * const SStateMachineKkeyPath = @"state";

@interface StateMachineModel()
@property(nonatomic,strong) StateMachine  * stateMachine;

@end
@implementation StateMachineModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        _stateMachine = [[StateMachine alloc]init];
        _currentType = [StateMachine getStateTypeEnum:_stateMachine.state];
        [_stateMachine addObserver:self forKeyPath:SStateMachineKkeyPath options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (keyPath == SStateMachineKkeyPath) {
        SStateType currentStateType = _currentType;
        SStateType nextStateType = [StateMachine getStateTypeEnum:change[@"new"]];
        _currentType = nextStateType;
        
        if (_delegate && [_delegate respondsToSelector:@selector(stateMachineModel:changeFromState:to:)]) {
            [_delegate stateMachineModel:self changeFromState:currentStateType to:nextStateType];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (BOOL)performEventWithEventType:(SEventType)eventType {
    return [self.stateMachine performEventWithEventType:eventType];
}

@end

